package cn.ubeta.b2c.product;

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import cn.ubeta.b2c.EmbeddedData;
import cn.ubeta.b2c.R;
import cn.ubeta.b2c.api.ApiProduct;
import cn.ubeta.b2c.bean.FoundInfo;
import cn.ubeta.b2c.bean.PriceInfo;
import cn.ubeta.b2c.bean.ProductInfo;
import cn.ubeta.b2c.common.CartCommon;
import cn.ubeta.b2c.common.ListFragment;
import cn.ubeta.b2c.common.ListFragmentConfig;
import cn.ubeta.b2c.utils.DensityUtil;
import cn.ubeta.b2c.utils.ToastHelper;
import cn.ubeta.b2c.widget.recyclerview.BaseViewHolder;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.GONE;

/**
 * Created by denny on 2016/10/13.
 */

public class ProductListFragment extends ListFragment<ProductInfo> {

    private static final String PARAM_ID = "id";

    private int mId;

    /**
     * 获取实例
     */
    public static ProductListFragment newInstance(int id) {
        ProductListFragment fragment = new ProductListFragment();
        Bundle args = new Bundle();
        args.putInt(PARAM_ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected ListFragmentConfig getConfig() {
        if (getArguments() != null) {
            mId = getArguments().getInt(PARAM_ID);
        }
        if (mId > 0) {
            return new ListFragmentConfig(R.layout.item_cart, 1, 2);
        } else {
            return new ListFragmentConfig(R.layout.item_product, 2, 4);
        }
    }

    @Override
    protected void bindItemView(BaseViewHolder helper, ProductInfo item) {
        // 商品图片
        //String url = item.getImgUrl();
        int listImg = item.getListImg();
        SimpleDraweeView img = helper.getView(R.id.iv_product);
        setResImage(img, listImg);

        // 跳转详情
        helper.convertView.setOnClickListener(v -> {
            if (item.getPrice() == 0)
                ToastHelper.show("暂无价格，请稍后重试");
            else
                ProductDetail.gotoDetail(getContext(), item);
        });

        // 商品标题
        String name = item.getName();
        if (!TextUtils.isEmpty(name)) {
            ((TextView) helper.getView(R.id.tv_name)).setText(name);
        }

        // 商品价格
        TextView tvPrice = helper.getView(R.id.tv_price);
        tvPrice.setText(item.getDisplayPrice());

        // 添加购物车
        //helper.getView(R.id.tv_add_cart).setOnClickListener(v -> CartCommon.add2Cart(item.getSkuId()));
        // 立即购买
        View cntView = helper.getView(R.id.tv_count);
        if (cntView != null && cntView.getVisibility() != GONE) {
            cntView.setVisibility(GONE);
            helper.getView(R.id.cb_cart).setVisibility(GONE);
            helper.getView(R.id.tv_add_cart).setVisibility(View.VISIBLE);
        }
        helper.getView(R.id.tv_add_cart).setOnClickListener(v -> {
            if (item == null || item.getPrice() == 0)
                ToastHelper.show("暂无价格，请稍后重试");
            else
                CartCommon.checkout(getActivity(), item);
        });

        /*
        有模型产品用红框标示
        RoundingParams p = img.getHierarchy().getRoundingParams();
        if (item.hasModel()) {
            p.setBorderWidth(6);
            p.setBorderColor(getResources().getColor(R.color.jd_red));
        } else {
            p.setBorderWidth(2);
            p.setBorderColor(getResources().getColor(R.color.GY4));
        }
        img.getHierarchy().setRoundingParams(p);
        */
    }

    @Override
    protected void loadData(int page) {
        // 首页先填充内置数据，然后拉取价格
        if (mId == 0) {
            //bindData(null);
        }

        ApiProduct.getProductPrice(mId, new Callback<PriceInfo>() {
            @Override
            public void onResponse(Call<PriceInfo> call, Response<PriceInfo> res) {
                if (res == null || res.body() == null) {
                    ToastHelper.show("获取价格错误，服务端错误");
                    return;
                }
                bindData(res.body().getData());
            }

            @Override
            public void onFailure(Call<PriceInfo> call, Throwable t) {
                // TODO getNetworkCallback().onFailure(t);
            }
        });
    }

    /**
     * 绑定品牌列表
     */
    private void bindData(List<PriceInfo> priceInfos) {
        // 商品信息填充价格
        List<ProductInfo> result = EmbeddedData.fillPriceInfo(mId, priceInfos);
        getNetworkCallback().onResponse(result);

        if (mId > 0) {
            return;
        }

        // 绑定品牌列表
        int dp4 = DensityUtil.dip2px(getContext(), 4);
        int dp8 = 2 * dp4;
        if (mAdapter.getHeaderViewsCount() == 0) {
            List<FoundInfo> brandInfos = EmbeddedData.getBrands(false);
            LinearLayout brandLayout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_brand_list, null);
            for (FoundInfo info : brandInfos) {
                LinearLayout brand = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_brand, null);
                // 品牌图片
                setResImage((SimpleDraweeView)brand.findViewById(R.id.iv_brand), info.getResImg(), false);
                // 品牌名字
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(0, dp4, 0, dp4);
                brand.setOnClickListener(v -> gotoBrand(info.getName(), info.getBrandId()));
                brandLayout.addView(brand, params);
            }
            // 底部灰色条
            View divider = new View(getContext());
            divider.setBackgroundColor(getResources().getColor(R.color.brand_divider));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp8 * 2);
            params.setMargins(0, dp8, 0, 0);
            divider.setLayoutParams(params);
            brandLayout.addView(divider);

            TextView tv = new TextView(getContext());
            tv.setText("-为您推荐-");
            tv.setTextColor(getResources().getColor(R.color.red));
            tv.setTextSize(18);
            params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER;
            params.setMargins(0, dp8, 0, dp8);
            tv.setLayoutParams(params);
            brandLayout.addView(tv);
            mAdapter.addHeaderView(brandLayout);
            mLayoutMan.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position == 0)
                        return getSpanCount();
                    return 1;
                }
            });
        }
    }

    /**
     * 跳转到品牌商品列表
     * @param title
     */
    private void gotoBrand(String title, int id) {
        ProductListActivity.gotoProductList(getActivity(), title, id);
    }

    /**
     * 设置图片
     * @param img
     * @param listImg
     */
    public static void setResImage(SimpleDraweeView img, int listImg) {
        setResImage(img, listImg, true);
    }

    public static void setResImage(SimpleDraweeView img, int listImg, boolean center) {
        if (listImg > 0) {
            //img.setImageResource(listImg);
            Uri uri = Uri.parse("res:///" + listImg);
            RoundingParams roundParams =  img.getHierarchy().getRoundingParams();
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setUri(uri)
                    .build();
            img.setController(controller);
            // 居中，圆边
            if (center) {
                img.getHierarchy().setRoundingParams(roundParams);
                img.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_INSIDE);
            } else {
                img.getHierarchy().setRoundingParams(null);
                img.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
            }
        } else {
            GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(img.getResources());
            GenericDraweeHierarchy hierarchy = builder
                    .setFadeDuration(300)
                    .setPlaceholderImage(R.drawable.placeholder_small)
                    .build();
            img.setHierarchy(hierarchy);
        }
    }
}
